<template>
  <div class="wrapper">
    <div class="top">
      <div>
        <h3>订单编号</h3>
        <h5>{{ payOrder.order_code }}</h5>
      </div>
      <div>
        <h3>订单金额</h3>
        <h5 class="price">￥{{ payOrder.subtotal }}</h5>
      </div>
    </div>
    <div class="pay">
      <div class="item" @click="beforePay">
        <div class="img">
          <img src="" alt="">
        </div>
        <div class="name">
          <div>
            <h3>微信支付</h3>
            <h5>微信安全支付</h5>
          </div>
        </div>
      </div>
      <div class="item" @click="balancePay" v-if="this.userState == 2">
        <div class="img">
          <img src="" alt="">
        </div>
        <div class="name">
          <div>
            <h3>余额支付</h3>
            <h5>当前余额: <span>￥{{ balance }}</span></h5>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import { addInt, removeInt } from '@/assets/js/axios.js'
  export default {
    name: 'Payment',
    created() {
      if (this.userState == 2) {
        removeInt()
        this._getBalance()
      }
    },
    data() {
      return {
        balance: ''
      }
    },
    computed: {
      ...mapState(['openId', 'payOrder', 'userState'])
    },
    methods: {
      async _getBalance() {
        try{
          let { data: { code, data } } = await this.$axios({
            url: '/v1/platform/balance',
            method: 'GET',
            params: {
              openid: this.openId
            }
          })
          if (code === 0) {
            this.balance = data
          } else if(code === 1) {
            this.balance = 0
          }
          addInt()
          this.$toast.clear()
        }catch(e){
          this.$toast(e)
        }
      },
      balancePay() {
        if (this.balance < this.payOrder.subtotal) {
          this.$toast('余额不足')
          return
        }
        this.$confirm('使用余额支付？').then(() => {
          this._balancePay()
        })
      },
      async _balancePay() {
        let { data: { code } } = await this.$axios({
          url: '/v1/platform/pay',
          method: 'POST',
          data: {
            order_code: this.payOrder.order_code,
            subtotal: Number(this.payOrder.subtotal),
            openid: this.openId
          }
        })
        if (code === 0) {
          this.$router.replace('/payComplete')
        }
      },
      async beforePay() {
        let formData = new FormData()
        formData.append('uid', this.payOrder.uid)
        formData.append('oid', this.payOrder.id)
        formData.append('totalFee', Number(this.payOrder.subtotal))
        formData.append('orderName', 'WowSurprise有惊喜')
        formData.append('openid', this.openId)
        formData.append('outTradeNo', this.payOrder.order_code)
        let { data: { code, data } } = await this.$axios({
          url: '/v1/wechat/pay',
          method: 'POST',
          data: formData
        })
        if(code === 0) {
          this.$toast.loading({
            message: 'Loading...',
            forbidClick: true,
            loadingType: 'spinner',
            duration: 0
          })
          this.Pay(data.package)
        }
      },
      Pay (data) {
        let vm = this
        if (typeof WeixinJSBridge === 'undefined') {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false)
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data))
            document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data))
          }
        } else {
          vm.onBridgeReady(data)
        }
      },
      onBridgeReady (data) {
        this.$toast.clear()
        let self = this
        /* eslint-disable */
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest', {
            'appId': data.appId,
            'timeStamp': String(data.timeStamp),    //这里必须要转换为字符串。ios跟android表现不同。后台返回的是数值，但是微信方面必须要json参数都是字符串形式，android会自动转换成字符串（当时我在这里也找了很久的博文才知道的）
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': data.signType,
            'paySign': data.paySign
          },
          function (res) {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              // self.$router.replace('/payComplete')
              window.location.href = 'http://www.youjingxi.net.cn/h5/#/payComplete'
            } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              self.$toast('支付取消!')
            } else {
              self.$toast('支付失败!')
            }
          }
        )
        /* eslint-enable */
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '@/assets/css/base.scss';
  .wrapper {
    padding-top: 0.2rem;
    min-height: 100vh;
    background: #eee;
  }
  .top {
    padding: 0 0.2rem;
    background: #fff;
    div {
      display: flex;
      height: 0.8rem;
      line-height: 0.8rem;
      border-bottom: 1px solid $bgGray;
      h3 {
        flex: 1;
        font-size: 0.24rem;
      }
      h5 {
        flex: 0 0 1rem;
        text-align: right;
        font-size: 0.24rem;
      }
      .price {
        color: $colorRed;
      }
    }
  }
  .pay {
    margin-top: 0.2rem;
    padding: 0 0.2rem;
    background: #fff;
    .item {
      display: flex;
      align-items: center;
      border-bottom: 1px solid $bgGray;
      .img {
        flex: 0 0 1rem;
        padding: 0.1rem;
        width: 1rem;
        height: 1rem;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .name {
        flex: 1;
        div {
          padding-left: 0.1rem;
          border-left: 1px solid $bgGray;
          font-size: 0.24rem;
          
          h5{
            color: $colorGray;
            span {
              color: $colorRed;
            }
          }
        }
      }
    }
  }
</style>
